package com.ruoyi.web.controller.combat.weibo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.Img;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.CombatMethod;
import com.ruoyi.combat.domain.useralignment.CombatUserWb;
import com.ruoyi.combat.domain.userlocation.CombatUser;
import com.ruoyi.combat.service.useralignment.ICombatUserWbService;
import com.ruoyi.combat.service.userlocation.ICombatUserService;
import com.ruoyi.combat.util.weibo.WeiboApiUtil;
import com.ruoyi.combat.util.weibo.WeiboOAuth;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "微博：操作接口")
@RestController
@RequestMapping("/weibo")
public class WeiboController extends BaseController {

    @Value("${weibo.appKey}")
    private String App_Key;

    @Value("${weibo.appSecret}")
    private String App_Secret;

    @Value("${weibo.redirectUri}")
    private String redirect_uri;

    @Autowired
    private ICombatUserService combatUserService;
    @Autowired
    private ICombatUserWbService combatUserWbService;
    @Autowired
    private WeiboApiUtil weiboApiUtil;

    /**
     *
     */
    @Anonymous
    @GetMapping("/getAuthUrl")
    @ApiOperation("获取授权链接")
    public AjaxResult auth(@RequestParam(value = "phoneNum") String phoneNum) {
        String url = "https://api.weibo.com/oauth2/authorize?client_id=" + App_Key +
                "&redirect_uri=" + redirect_uri + "&scope=all&response_type=code";
        if(StringUtils.isNotEmpty(phoneNum)){
            url = url + "&state=" + phoneNum;
        }

        Map<String,String> data = new HashMap();
        data.put("url",url);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            BufferedImage image = QrCodeUtil.generate(url, 300, 300);

            boolean flag = ImageIO.write(image, "png", out);
            byte[] b = out.toByteArray();
            String imageBase64 = Base64.getEncoder().encodeToString(b);
            data.put("image",imageBase64);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return AjaxResult.success(data);
    }

    @Anonymous
    @GetMapping("/getTocken")
    @ApiOperation("授权回调接口")
    public AjaxResult getToken(@RequestParam("code") String code,@RequestParam("state") String state) {
        String url = "https://api.weibo.com/oauth2/access_token";
        Map data = new HashMap();
        data.put("client_id", App_Key);
        data.put("client_secret", App_Secret);
        data.put("grant_type", "authorization_code");
        data.put("code", code);
        data.put("redirect_uri", redirect_uri);

        String post = HttpUtil.post(url, data);
        System.out.println(post);
        Map bean = JSONUtil.toBean(post, Map.class);
        Object o = bean.get("access_token");
        Object uid = bean.get("uid");
        if(o!=null&&uid!=null){
            String token = String.valueOf(o);
            String uidStr = String.valueOf(uid);
            CombatUser combatUser = new CombatUser();
            combatUser.setUserPhone(state);
            List<CombatUser> combatUserList = combatUserService.selectCombatUserList(combatUser);
            if(combatUserList.size()>0){
                CombatUser combatUser1 = combatUserList.get(0);
                combatUser1.setToken(token);
                combatUser1.setUserId(uidStr);
                combatUser1.setUpdateTime(new Date());
                combatUserService.updateCombatUser(combatUser1);
            }
            CombatUserWb combatUserWb = new CombatUserWb();
            combatUserWb.setUserPhone(state);
            List<CombatUserWb> combatUserWbList = combatUserWbService.selectCombatUserWbList(combatUserWb);
            if(combatUserWbList.size()>0){
                CombatUserWb combatUserWb1 = combatUserWbList.get(0);
                combatUserWb1.setToken(token);
                combatUserWb1.setUserId(uidStr);
                combatUserWb1.setUpdateTime(new Date());
                combatUserWbService.updateCombatUserWb(combatUserWb1);
            }
        }
        return AjaxResult.success("scucess");
    }


    /*@Anonymous
    @GetMapping("/getUserInfoByName")
    @ApiOperation("通用呢称获取用户信息")
    public AjaxResult getUserInfoByName(String name){





        return AjaxResult.success();

    }
*/
    @Anonymous
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(@RequestBody List<String> ids){
        return AjaxResult.success(weiboApiUtil.getLatestWeibo(ids));
    }




}
